package com.sen.common.user.config;

import cn.hutool.core.util.StrUtil;
import com.sen.common.common.bo.PeopleInfo;
import com.sen.common.common.constrant.CommonConstrant;
import com.sen.common.common.util.JacksonUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * 基础信息过滤器
 * @author esjiang
 */
@ConditionalOnClass(Filter.class)
public class UserFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException {
        try {
            String userName = request.getParameter(CommonConstrant.X_USER_HEADER) ;
            if (StrUtil.isBlank(userName)){
                userName = request.getHeader(CommonConstrant.X_USER_HEADER) ;
            }
            if (StrUtil.isNotBlank(userName)){
                UserContextHolder.setUser(URLDecoder.decode(userName, "utf-8"));
            }
            String peopleInfoJson = request.getParameter(CommonConstrant.X_PEOPLE_HEADER);
            if (StrUtil.isBlank(peopleInfoJson)){
                peopleInfoJson = request.getHeader(CommonConstrant.X_PEOPLE_HEADER) ;
                if (StrUtil.isNotBlank(peopleInfoJson)){
                    peopleInfoJson = URLDecoder.decode(peopleInfoJson, "utf-8");
                }
            }
            if (StrUtil.isNotBlank(peopleInfoJson)){
                UserContextHolder.setPeople(JacksonUtils.toObject(peopleInfoJson, PeopleInfo.class));
            }
            filterChain.doFilter(request, response);
        } finally {
            UserContextHolder.clear();
        }
    }


}
